import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

class ComplexTypeDeclaration extends Node {
	private Node type_;
	private String name_;
	private Node block_;
	private String ename_;
	private List<Node> children;

	public ComplexTypeDeclaration(Node t, String n, Node b, String en) {
		type_ = t;
		name_ = n;
		block_ = b;
		ename_ = en;
		children = new ArrayList<Node>();
		children.add(type_);
		children.add(new StringNode(name_));
		children.add(new StringNode("extends"));
		children.add(new StringNode(en));
		children.add(block_);
	}

	public ComplexTypeDeclaration(Node t, String n, Node b) {
		type_ = t;
		name_ = n;
		block_ = b;
		children = new ArrayList<Node>();
		children.add(type_);
		children.add(new StringNode(name_));
		children.add(block_);
	}

	public void print(PrintWriter pw) {
		pw.println("Node name : ComplexTypeDeclaration. Class name is: "
				+ name_);
		type_.print(pw);
		if (ename_ != null) {
			pw.println("Extends Class name is: " + ename_);
		}
		block_.print(pw);
	}

	public String translate(HashMap<String, PrintWriter> pws, String condition, SymbolTable rt,
			String parent) {
		rt.getStack().push(name_);	
		String pwFile = "output/" + name_ + ".java";
		
		Symbol sy = new Symbol(name_, type_, true, "", ename_);
		rt.getTables().add(sy);
		
		if(ename_ != null) {
			System.out.println("ename_: " + ename_);
			for(int i = 0; i < rt.getTables().size(); i++) {
				Symbol temp = rt.getTables().get(i);
				// System.out.println("temp.getScopes(): " + temp.getScopes().size());
				for(int j = 0; j < temp.getScopes().size(); j++) {
					String s = temp.getScopes().get(j);
					String stemp = "";
					
					if(s != null && s != "") {
						stemp = s.substring(0, s.length() - 1);
					}
					
					System.out.println("temp" + j + ": " + stemp);
					if(stemp.trim().equals(ename_)) {
						temp.getScopes().add(name_);
						break;
					}
				}
			}
		}
		
		try {
			PrintWriter temp = new PrintWriter(pwFile);
			pws.put(rt.getStack().get(1), temp);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		System.out.println("Complex pushed: " + name_);
		String type = type_.translate(pws, null, rt, parent);
		String scope = "";
		
		String key = rt.getStack().get(1);
		PrintWriter pw = pws.get(key);
		System.out.println(pw);
		
		if (ename_ != null) {
			pw.print("public class " + name_ + " extends " + ename_);
		} else if (type.equals("Panel")) {
			pw.print("public class " + name_ + " extends JFrame");
		} else {
			pw.print("public class " + name_);
		}

		block_.translate(pws, null, rt, scope);
		return null;

	}

}
